# coding=utf-8
from random import randrange
import pygame

# 初始化游戏
pygame.init()

# 设置窗口大小
width, height = 800, 800
screen = pygame.display.set_mode((width, height))

# 蛇身
she = [pygame.Rect(10,10, 10, 10)]
shiwu = None
score = 0
font = pygame.font.SysFont('simhei', 50)
dead = False


# 设置窗口填充色，RGB颜色代码
screen.fill((0, 255, 255))


up = (0, -10)
down = (0, 10)
left = (-10, 0)
right = (10, 0)

dir = right


clock = pygame.time.Clock()

while True:


    clock.tick(min(7 + (len(she) / 1), 20))


    event = pygame.event.poll()

    if event.type == pygame.QUIT:
        pygame.quit()

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP and dir != down:
            dir = up
        if event.key == pygame.K_DOWN and dir != up:
            dir = down
        if event.key == pygame.K_LEFT and dir != right:
            dir = left
        if event.key == pygame.K_RIGHT and dir != left:
            dir = right
            
    screen.fill((0,255,255))
    if dead:
    	screen.fill((0, 0, 0))
    	surface = font.render(u"Game Over 分数:" + str(score), True, (255,255,255))
    	screen.blit(surface, (200, 0))
    
    if shiwu is None:
        shiwu = pygame.Rect(randrange(48) * 10, randrange(48) * 10, 10, 10)

    pygame.draw.rect(screen, (138, 43, 226), shiwu)

    for rect in she:
        pygame.draw.rect(screen, (199, 97, 20), rect)

    node = she[-1].move(dir)
    if node in she or node.left > width or node.top > height or node.left < 0 or node.top < 0:
    	dead = True
    if node == shiwu:
        shiwu = None
        score = score + 1
    else:
        del she[0]
    she.append(node)
    surface = font.render(u'分数'+str(score),True,(0,0,0))
    screen.blit(surface,(30,30))
    pygame.display.flip()
